package org.byd.dmsja.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@CrossOrigin
@RestController
@RequestMapping("/api/file")
public class FileController {

    // 配置上传文件存储路径（可在application.properties中设置）
    @Value("${file.upload-dir}")
    private String uploadDir;

    // 文件上传
    @PostMapping("/upload")
    public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file) throws JsonProcessingException {
        Map<String,String> map = new HashMap<>();
        ObjectMapper objectMapper = new ObjectMapper();

        try {
            if (file.isEmpty()) {
                return ResponseEntity.badRequest().body("文件为空");
            }

            // 生成唯一文件名（避免重复）
            String fileName = UUID.randomUUID() + "_" + file.getOriginalFilename();
            Path path = Paths.get(uploadDir, fileName);

            // 保存文件到本地
            Files.copy(file.getInputStream(), path, StandardCopyOption.REPLACE_EXISTING);
            map.put("svrFileName",fileName);
            map.put("cliFileName",file.getOriginalFilename());
            map.put("message","文件上传成功");
            String json = objectMapper.writeValueAsString(map);

            return ResponseEntity.ok(json);
        } catch (IOException e) {
            map.put("svrFileName","");
            map.put("cliFileName","");
            map.put("message","文件上传失败");
            String json = objectMapper.writeValueAsString(map);
            return ResponseEntity.internalServerError().body(json);
        }
    }
}
